/*
 *  Copyright 2009 Matthieu Chase Heimer
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.

 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.

 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */
package com.macro10.xroads.commands;

import com.macro10.switchboard.AbstractCommand;
import com.macro10.switchboard.Request;
import com.macro10.switchboard.Session;
import com.macro10.switchboard.service.UserTransaction;
import com.macro10.xroads.entity.Avatar;
import com.macro10.xroads.service.AvatarService;
import java.util.List;

/**
 * Requires headers:
 * Filters: require_admin
 */
public class ListAvatars extends AbstractCommand {

    @Override
    public ExecuteResult execute(Request request, Session session) {
        UserTransaction ut = null;
        try {
            ut = new UserTransaction();
            AvatarService avatarService = new AvatarService(ut);
            List<Avatar> avatars = avatarService.getAllAvatars();
            if (avatars.size() == 0) {
                session.writeError(request.getURL() + ":no.avatars");
            } else {
                session.writeText(request.getURL() + ":avatar.list");
                for (Avatar avatar : avatars) {
                    session.writeText(avatar.getAvatarId());
                }
            }
            ut.commit();
        } catch (Exception e) {
            session.writeException(request.getURL() + ":avatar.listing.failed", e);
            if (ut != null) {
                ut.rollback();
            }
        }
        return ExecuteResult.START_POST;
    }
}
